#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <mosquitto.h>

static volatile int running = 1;

void signal_handler(int sig) {
    printf("\n收到信号 %d，正在退出...\n", sig);
    running = 0;
}

void on_connect(struct mosquitto *mosq, void *obj, int rc) {
    printf("连接回调: rc=%d\n", rc);
    if (rc == 0) {
        printf("✅ 连接成功！\n");
        printf("📤 订阅主题: device/command\n");
        mosquitto_subscribe(mosq, NULL, "device/command", 1);
    } else {
        printf("❌ 连接失败: ");
        switch(rc) {
            case 1: printf("协议版本不支持\n"); break;
            case 2: printf("客户端ID不合法\n"); break;
            case 3: printf("代理服务器不可用\n"); break;
            case 4: printf("用户名或密码错误\n"); break;
            case 5: printf("未授权\n"); break;
            default: printf("未知错误 (%d)\n", rc); break;
        }
    }
}

void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) {
    printf("📨 收到消息:\n");
    printf("   主题: %s\n", msg->topic);
    printf("   内容: %.*s\n", msg->payloadlen, (char*)msg->payload);
    
    // 简单的命令处理
    if (strcmp(msg->topic, "device/command") == 0) {
        char *payload = malloc(msg->payloadlen + 1);
        memcpy(payload, msg->payload, msg->payloadlen);
        payload[msg->payloadlen] = '\0';
        
        if (strcmp(payload, "status") == 0) {
            printf("📤 响应状态查询\n");
            mosquitto_publish(mosq, NULL, "device/status", 
                            strlen("{\"status\":\"online\"}"), 
                            "{\"status\":\"online\"}", 1, 0);
        }
        
        free(payload);
    }
}

void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) {
    printf("📋 订阅成功 (ID: %d, QoS: %d)\n", mid, granted_qos[0]);
}

void on_publish(struct mosquitto *mosq, void *obj, int mid) {
    printf("📤 消息发送成功 (ID: %d)\n", mid);
}

int main() {
    struct mosquitto *mosq = NULL;
    int rc;
    
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    
    printf("=== 简化完整版MQTT客户端测试 ===\n");
    printf("代理: localhost:1883\n");
    printf("客户端ID: simple_full_client\n");
    printf("按 Ctrl+C 退出\n\n");
    
    // 初始化
    mosquitto_lib_init();
    
    // 创建实例
    mosq = mosquitto_new("simple_full_client", true, NULL);
    if (!mosq) {
        printf("❌ 创建mosquitto实例失败\n");
        return 1;
    }
    
    // 设置回调
    mosquitto_connect_callback_set(mosq, on_connect);
    mosquitto_message_callback_set(mosq, on_message);
    mosquitto_subscribe_callback_set(mosq, on_subscribe);
    mosquitto_publish_callback_set(mosq, on_publish);
    
    // 连接
    printf("🔌 连接到 localhost:1883...\n");
    rc = mosquitto_connect(mosq, "localhost", 1883, 60);
    if (rc != MOSQ_ERR_SUCCESS) {
        printf("❌ 发起连接失败: %s\n", mosquitto_strerror(rc));
        mosquitto_destroy(mosq);
        mosquitto_lib_cleanup();
        return 1;
    }
    
    // 启动网络循环
    printf("🔄 启动网络循环...\n");
    rc = mosquitto_loop_start(mosq);
    if (rc != MOSQ_ERR_SUCCESS) {
        printf("❌ 启动网络循环失败: %s\n", mosquitto_strerror(rc));
        mosquitto_destroy(mosq);
        mosquitto_lib_cleanup();
        return 1;
    }
    
    // 等待连接建立
    printf("⏳ 等待连接建立...\n");
    sleep(3);
    
    // 发送初始状态
    printf("📤 发送初始状态消息\n");
    mosquitto_publish(mosq, NULL, "device/status", 
                     strlen("{\"status\":\"initialized\"}"), 
                     "{\"status\":\"initialized\"}", 1, 0);
    
    // 主循环
    int heartbeat_count = 0;
    while (running) {
        sleep(10);  // 每10秒发送一次心跳
        
        if (running) {
            char heartbeat[128];
            snprintf(heartbeat, sizeof(heartbeat), 
                    "{\"heartbeat\":%d,\"timestamp\":%ld}", 
                    ++heartbeat_count, time(NULL));
            
            printf("💗 发送心跳: %s\n", heartbeat);
            mosquitto_publish(mosq, NULL, "device/heartbeat", 
                            strlen(heartbeat), heartbeat, 0, 0);
        }
    }
    
    // 发送离线消息
    printf("📤 发送离线消息\n");
    mosquitto_publish(mosq, NULL, "device/status", 
                     strlen("{\"status\":\"offline\"}"), 
                     "{\"status\":\"offline\"}", 1, 1);
    
    sleep(1);  // 等待消息发送
    
    // 清理
    printf("🧹 清理资源...\n");
    mosquitto_loop_stop(mosq, true);
    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();
    
    printf("✅ 程序正常退出\n");
    return 0;
}

/*
编译: gcc -o mqtt_simple_full mqtt_simple_full.c -lmosquitto
运行: ./mqtt_simple_full

测试命令:
mosquitto_sub -h localhost -t "device/+" -v
mosquitto_pub -h localhost -t "device/command" -m "status"
*/